
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const favicon = require('serve-favicon');
const log4js = require('./utils/logger').log4js;
const Logger = require("./utils/logger").Logger("access");

let app = express();

app.use(require('./utils/middleware'));
app.use(favicon(path.join(__dirname, "public/favicon.ico")));   //定义icon图标
app.use(bodyParser.json({limit: '1mb'}));       //定义数据解析器
app.use(bodyParser.urlencoded({limit: '1mb', extended: true})); //定义url编码方式，

app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);

app.use(function (req, res, next) {
    //记录IP，访问人，请求地址，请求方式，请求参数（params：路由参数 query：get参数 body：post等参数）
    Logger.info('ip:' + req.ip +
        '  url:' + req.url + '  method:' + req.method + '  params:' + JSON.stringify(req.params) +
        '  query:' + JSON.stringify(req.query) + '  body:' + JSON.stringify(req.body));
    next();
});

//配置response日志
app.use(log4js.connectLogger(Logger, {
    level: 'INFO',
    //       访问IP           请求方式        路由      处理状态        响应花费时间
    format: 'ip::remote-addr  method::method  url::url  status::status  response-time::response-time' + 'ms'
}));


app.use('/', require('./routes'));

/**
 * 拦截所有的结果，如果是错误写入日志
 */
app.use(function (err, req, res, next) {
    if (err) {
        let error = {method: req.method, url: req.originalUrl, message: err.message, stack: err.stack};
        // console.log(error)
        log4js.getLogger('ERROR').error(JSON.stringify({error: error}));
    }

    res.error(err, err.status || 500)
});

//404错误处理
app.use(function (req, res) {
    Logger.error(req.method, req.originalUrl, " 404");
    let err = new Error('Not Found');
    err.status = 404;
    res.error(err, err.status)
});

module.exports = app;